package com.partner.frame.support.util;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.security.*;

public class CommonUtil
{
   private static final int SEQ_MAX_VALUE = 9999;
   private static final int SEQ_MIN_VALUE = 1001;
   
   private static Integer SynSeqLock = new Integer(0);
   private static int msgSEQ = 0;

   public CommonUtil()
   {
   }

   public static String generateSeq()
   {
      String strSeq = "";

      synchronized(SynSeqLock)
      {
         msgSEQ++;
         if(msgSEQ > SEQ_MAX_VALUE || msgSEQ < SEQ_MIN_VALUE) msgSEQ = SEQ_MIN_VALUE;

         strSeq = formatDateTime() + Integer.toString(msgSEQ);
      }

      return strSeq;
   }

   public static String encodeBase64(byte[] btData)
   {
      String strEncodeValue = null;
      

      try
      {
         strEncodeValue = org.apache.commons.codec.binary.Base64.encodeBase64String(btData);
      }
      catch(Exception eData)
      {
         eData.printStackTrace();
      }

      return strEncodeValue;
   }

   public static byte[] decodeBase64(String strValue)
   {
      byte[] btData;

      try
      {
         btData = org.apache.commons.codec.binary.Base64.decodeBase64(strValue);
      }
      catch(Exception eData)
      {
         btData = null;
         eData.printStackTrace();
      }

      return btData;
   }

   public static byte[] computeMD5(byte[] btSource)
   {
      byte[] btDest = null;

      try
      {
         MessageDigest msgDigest = MessageDigest.getInstance("MD5");
         msgDigest.reset();
         msgDigest.update(btSource);
         btDest = msgDigest.digest();
      }
      catch(Exception eCompute)
      {
         System.out.println("CommonUtils::computeMD5 - Exception - " + eCompute.toString());
         eCompute.printStackTrace();
      }

      return btDest;
   }

   public static String formatDateTime()
   {
      Calendar now = Calendar.getInstance();
      String year = Integer.toString(now.get(Calendar.YEAR));
      String mon = Integer.toString(now.get(Calendar.MONTH) + 1);
      String day = Integer.toString(now.get(Calendar.DAY_OF_MONTH));
      String hour = Integer.toString(now.get(Calendar.HOUR_OF_DAY));
      String min = Integer.toString(now.get(Calendar.MINUTE));
      String sec = Integer.toString(now.get(Calendar.SECOND));

      mon = (mon.length() == 1) ? "0" + mon : mon;
      day = (day.length() == 1) ? "0" + day : day;
      hour = (hour.length() == 1) ? "0" + hour : hour;
      min = (min.length() == 1) ? "0" + min : min;
      sec = (sec.length() == 1) ? "0" + sec : sec;

      return (year + mon + day + hour + min + sec);
   }

   public static int saveFileData(String strFile, byte[] btFile)
   {
      int nResult = 0;
      String strDestFile = "";
      OutputStream osFile = null;

      try
      {
         strDestFile = strFile;
         osFile = new FileOutputStream(strDestFile);

         osFile.write(btFile);
      }
      catch(Exception eLoad)
      {
         nResult = -1;
         eLoad.printStackTrace();
      }
      finally
      {
         try
         {
            if(osFile != null) osFile.close();
         }
         catch(Exception eOS)
         {
         }

         osFile = null;
      }

      return nResult;
   }

   public static int saveUploadFile(File fileSrc, String strSaveFile)
   {
      int nResult = 0;
      String strDestFile = "";
      InputStream isFile = null;
      OutputStream osFile = null;

      try
      {
         strDestFile = strSaveFile;
         isFile = new FileInputStream(fileSrc);
         osFile = new FileOutputStream(strDestFile);

         int nCount = 0;
         byte[] btData = null;
         btData = new byte[16 * 1024];
         do
         {
            nCount = isFile.read(btData, 0, 8192);
            if(nCount > 0) osFile.write(btData, 0, nCount);
         }
         while(nCount != -1);

      }
      catch(Exception eLoad)
      {
         nResult = -1;
         eLoad.printStackTrace();
      }
      finally
      {
         try
         {
            if(isFile != null) isFile.close();
         }
         catch(Exception eIS)
         {
         }
         try
         {
            if(osFile != null) osFile.close();
         }
         catch(Exception eOS)
         {
         }

         isFile = null;
         osFile = null;
      }

      return nResult;
   }

   public static String toHexDebug(byte[] btSource)
   {
      int i = 0, nValue = 0;
      String strDest = "", strTmp = "";

      if(btSource == null)   return null;
      try
      {
         for (i=0; i<btSource.length; i++)
         {
            if(i%16 == 0 && i>0)   strDest = strDest + "\n";
            nValue = (int)btSource[i];
            if(nValue < 0)   nValue = nValue + 256;
            strTmp = Integer.toHexString(nValue);
            if(strTmp.length() <= 1)
               strTmp = "0" + strTmp;  //仅有一位时，前面补0
            strDest += "[" + strTmp + "] ";
         }
      }
      catch(Exception e)
      {
         strDest = null;
      }
      
      return strDest;
   }
   
   //将字节数组转换为十六进制表示的字符串
   public static String convertBytesToString(byte[] btSource)
   {
      int i = 0, nValue = 0;
      String strDest = "", strTmp = "";

      if(btSource == null) return null;
      try
      {
         for(i = 0; i < btSource.length; i++)
         {
            nValue = (int) btSource[i];
            if(nValue < 0) nValue = nValue + 256;
            strTmp = Integer.toHexString(nValue);

            if(strTmp.length() <= 1) strTmp = "0" + strTmp; // 仅有一位时，前面补0

            strDest += strTmp;
         }
      }
      catch(Exception e)
      {
         strDest = null;
      }

      return strDest;
   }

   //将十六进制字字符串转换为字节数组
   public static byte[] convertStringToBytes(String srcBuff)
   {
      byte tmp = 0;
      int i = 0, j = 0;
      String subBuff = "";
      byte[] btResult = null;

      if(srcBuff == null) return null;
      try
      {
         btResult = new byte[srcBuff.length() / 2];
         for(i = 0, j = 0; i < srcBuff.length(); i += 2, j++)
         {
            subBuff = srcBuff.substring(i, i + 2);
            tmp = (byte) Integer.parseInt(subBuff, 16);
            btResult[j] = tmp;
         }
      }
      catch(Exception eData)
      {
         btResult = null;
      }

      return btResult;
   }
   public static String string2MD5(String inStr){
		MessageDigest md5 = null;
		try{
			md5 = MessageDigest.getInstance("MD5");
		}catch (Exception e){
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++){
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();

	}
   public static boolean isMobile(String mobile) {

		return Pattern.matches("^((13[0-9])|(14[5,7,9])|(15[^4,\\D])|(17[0,1,3,5-8])|(18[0-9]))\\d{8}$", mobile);
	}
   public static boolean pwdFormartError(String pwd) {
	   String SEARCHKEYREGEX = "[',*&#%()=]+";
	   Pattern p = Pattern.compile(SEARCHKEYREGEX);    
	   Matcher m = p.matcher(pwd); 
	   return m.find();
	}
   
   public boolean stringEmpty(String string) {
	if (string == null || "".equals(string)||"null".equalsIgnoreCase(string)||"undefined".equalsIgnoreCase(string)) {
		return true;
	}
	return false;
}
   public static void main(String[] args)
   {
      byte[] btData = null;
      // String strFile = "g:/0102_error.txt";
      String strInitPasswd = "123456", strPasswd = "", strArray = "[]";
      
//      btData = CommonUtil.computeMD5(strInitPasswd.getBytes());
//      strPasswd = CommonUtil.convertBytesToString(btData);
//      System.out.println("MD5(" + strInitPasswd + ") = [" + strPasswd + "]");

      btData = CommonUtil.computeMD5(strInitPasswd.getBytes());
      btData = CommonUtil.computeMD5(btData);
      strPasswd = CommonUtil.convertBytesToString(btData);
      System.out.println("MD5(MD5(" + strInitPasswd + ")) = [" + strPasswd + "]");

//      btData = CommonUtils.computeMD5(strPasswd.getBytes());
//      strPasswd = CommonUtils.convertBytesToString(btData);
//      btData = CommonUtils.computeMD5(strPasswd.getBytes());
//      strPasswd = CommonUtils.convertBytesToString(btData);
//      System.out.println("MD5(MD5(Passwd)) = [" + strPasswd + "]");

//      System.out.println(JSONArray.fromObject(strArray).toString());
//      
//      JSONArray jarrayTest = new JSONArray();
//      System.out.println(jarrayTest.toString());

   }

}